package com.example.testrecorder;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testrecorder.domain.Issue;
import com.example.testrecorder.domain.QueAndAns;
import com.example.testrecorder.domain.SelectItem;
import com.example.testrecorder.domain.User;
import com.example.testrecorder.utils.BitmapUtil;
import com.example.testrecorder.utils.CallSystemCameraOrAlbum;
import com.example.testrecorder.utils.DateUtil;
import com.example.testrecorder.utils.MyDialog;
import com.example.testrecorder.utils.PermissionUtil;
import com.example.testrecorder.utils.SelectDialog;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @author Yingyong Lao
 * 创建时间 2021/5/23 19:41
 * @version 1.0
 */
public class EditPerDataFragment extends Fragment {
    private Toolbar toolbar;
    private TextView accountTv,registerDateTv;
    private EditText trueNameEt,telEt,ageEt,emailEt;
    private Spinner genderSp;
    public Bitmap bitmapFromPath;
    public CircleImageView cv;
    private LinearLayout headPortraitLl;
    private Button saveBtn;
    private User currUser;
    public File imgFile;
    private SelectDialog selectDialog;
    private static final int CHOOSE_FROM_ALBUM=2;
    private String genderStr="其他";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_edit_per_data, container, false);
        toolbar=v.findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToViewFra();//跳转到查看个人资料的碎片
            }
        });
        currUser=MyApplication.currUser;
        cv=v.findViewById(R.id.cv);
        String headPortraitStr = currUser.getHeadPortraitStr();
        if(!TextUtils.isEmpty(headPortraitStr)){
            PersonalDataActivity activity= (PersonalDataActivity) getActivity();
            activity.imgPathStr=headPortraitStr;
           bitmapFromPath = BitmapUtil.getBitmapFromPath(headPortraitStr);
            PermissionUtil.reqWriteAndReadPermission(getActivity(), new PermissionUtil.PermittedCallBack() {
                @Override
                public void permitted() {
                    cv.setImageBitmap(bitmapFromPath);
                }
            });
        }
        headPortraitLl=v.findViewById(R.id.headPortraitLl);
        headPortraitLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<SelectItem> list=new ArrayList<>();
                list.add(new SelectItem(R.drawable.icons8_google_images_96px,"拍照"));
                list.add(new SelectItem(R.drawable.icons8_picture_96px,"从相册中选择"));
                selectDialog=new SelectDialog(getActivity(), list, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if(selectDialog!=null){
                            selectDialog.dismiss();
                        }
                        if(position==0){
                            PermissionUtil.reqRWCPermission(getActivity(), new PermissionUtil.PermittedCallBack() {
                                @Override
                                public void permitted() {
                                    bootCamera();
                                }
                            });
                        }else if(position==1){
                            openAlbum();//打开相册
                        }

                    }
                });
            }
        });
        accountTv=v.findViewById(R.id.accountTv);
        accountTv.setText(currUser.getUserName());
        trueNameEt=v.findViewById(R.id.trueNameEt);
        trueNameEt.setText(currUser.getTrueName());
        trueNameEt.requestFocus();
        telEt=v.findViewById(R.id.telEt);
        telEt.setText(currUser.getTel());
        emailEt=v.findViewById(R.id.emailEt);
        emailEt.setText(currUser.getEmail());
        ageEt=v.findViewById(R.id.ageEt);
        ageEt.setText(""+currUser.getAge());
        genderSp=v.findViewById(R.id.genderSp);
        genderSp.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1, new String[]{"男","女","其他"}));
        String gender = currUser.getGender();
        if("男".equals(gender)){
            genderSp.setSelection(0);
        }else if("女".equals(gender)){
            genderSp.setSelection(1);
        }else {
            genderSp.setSelection(2);
        }
        genderSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==0){
                    genderStr="男";
                }else if(position==1){
                    genderStr="女";
                }else {
                    genderStr="其他";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        registerDateTv=v.findViewById(R.id.registerDateTv);
        registerDateTv.setText(DateUtil.getFormatDateStr(currUser.getRegisterDate()));
        saveBtn=v.findViewById(R.id.saveBtn);
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currUser.setTrueName(trueNameEt.getText().toString());
                String tel = telEt.getText().toString();
                if(TextUtils.isEmpty(tel)){
                    MyDialog.showInfo(getActivity(),"保存失败，手机号不能为空！");
                    return;
                }
                List<User> users = LitePal.where("tel=? and id!=?", tel,""+currUser.getId()).find(User.class);
                if(users.size()>0){
                    MyDialog.showInfo(getActivity(),"保存失败，手机号已被占用！");
                    return;
                }
                currUser.setTel(tel);
                currUser.setEmail(emailEt.getText().toString());
                String ageStr = ageEt.getText().toString();
                currUser.setAge(Integer.parseInt(TextUtils.isEmpty(ageStr)?"":ageStr));
                currUser.setGender(genderStr);
                List<QueAndAns> list = LitePal.where("user_id=?", "" + currUser.getId()).find(QueAndAns.class);
                List<Issue> list2 = LitePal.where("user_id=?", "" + currUser.getId()).find(Issue.class);
                currUser.setQueAndAnsList(list);//这句话很关键，如果没有的话，密保表的外键就会被设置为0
                currUser.setIssueList(list2);//这句话很关键，如果没有的话，问题表的外键就会被设置为0
                PersonalDataActivity personalDataActivity= (PersonalDataActivity) getActivity();
                currUser.setHeadPortraitStr(personalDataActivity.imgPathStr);
                boolean save = currUser.save();
                if(save){
                    Toast.makeText(getActivity(),"保存成功！",Toast.LENGTH_SHORT).show();
                    goToViewFra();
                }else {
                    Toast.makeText(getActivity(),"保存失败！",Toast.LENGTH_SHORT).show();
                }
            }

        });

        return v;
    }
    private void goToViewFra() {
        PersonalDataActivity activity = (PersonalDataActivity) getActivity();
        FragmentTransaction fragmentTransaction = activity.fragmentManager.beginTransaction();
        ViewPerDataFragment viewPerDataFragment = new ViewPerDataFragment();
        fragmentTransaction.replace(R.id.container,viewPerDataFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    /**
     * 打开相机
     */
    private void bootCamera(){
        imgFile = CallSystemCameraOrAlbum.OpenCamera((AppCompatActivity) getActivity());//调用工具类来拍照
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        getActivity().startActivityForResult(intent, CHOOSE_FROM_ALBUM); // 打开相册
    }
}